
use std::io::{self, Write, Read};
use std::os::unix::net::UnixStream;
use std::process;

const SOCKET_NAME: &str = "/tmp/DemoSocket";
const BUFFER_SIZE: usize = 128;

fn main() {
    let mut addr = match UnixStream::connect(SOCKET_NAME) {
        Ok(stream) => stream,
        Err(err) => {
            eprintln!("The server is down. Error: {}", err);
            process::exit(1);
        }
    };

    while let Ok(_) = {
        println!("Enter number to send to server :");
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Failed to read line");
        let i: i32 = match input.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                eprintln!("Please type a number!");
                return;
            }
        };

        let ret = addr.write(&i.to_ne_bytes()).unwrap_or_else(|err| {
            eprintln!("write error: {}", err);
            process::exit(1);
        });

        println!("No of bytes sent = {}, data sent = {}", ret, i);

        if i == 0 { Err(()) } else { Ok(()) }
    } {}

    let mut buffer = [0u8; BUFFER_SIZE];
    let msg = "RES\0";
    addr.write_all(msg.as_bytes()).expect("Failed to write to socket");

    println!("buffer = {}", msg.trim_end_matches('\0'));

    let ret = addr.read(&mut buffer).unwrap_or_else(|err| {
        eprintln!("read error: {}", err);
        process::exit(1);
    });

    let result = String::from_utf8_lossy(&buffer[..ret]);

    println!("Result = {}", result);

    // Close socket is handled automatically when `addr` goes out of scope
}
